//
//  ZMYAutoReadViewController.m
//  QiYReader
//
//  Created by 奇阅科技 on 14/12/17.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ZMYAutoReadViewController.h"
#import "ReadConfig.h"
#import "Config.h"
@interface ZMYAutoReadViewController()
{
    ReadSchedule *readSchedule;
    BookChapterText *chapterText;
}
@end
@implementation ZMYAutoReadViewController
@synthesize pointsPerSecond = _pointsPerSecond;
-(void)viewDidLoad{
    [super viewDidLoad];
    readSchedule = [[ZMYLKDB getLKDBHelper]getReadSchedule:self.articleid];
    chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.articleid chapterId:readSchedule.chapterId];
    self.textView.tintColor = RGB_COLOR(116, 178, 77);
    self.view.backgroundColor = [ReadConfig currentAccount].bgColor;
    self.textView.pointsPerSecond = [ReadConfig currentAccount].pointsPerSecond;
    [self setTextHighlighted];
    self.titleNameLabel.text = chapterText.chapterName;
    self.titleNameLabel.textColor = [ReadConfig currentAccount].titleColor;
    
    self.percentageLabel.textColor = [ReadConfig currentAccount].titleColor;
    
    self.textView.readDelegate = self;
    self.textView.delegate = self;
    UIMenuItem *menuItem2 = [[UIMenuItem alloc]initWithTitle:@"高亮" action:@selector(highlighted)];
    UIMenuItem *menuItem22 = [[UIMenuItem alloc]initWithTitle:@"取消高亮" action:@selector(cancelHighlighted)];
//    UIMenuItem *menuItem3 = [[UIMenuItem alloc]initWithTitle:@"笔记" action:@selector(bookNote)];
//    UIMenuItem *menuItem33 = [[UIMenuItem alloc]initWithTitle:@"删除笔记" action:@selector(deleteBookNote)];
    UIMenuItem *menuItem4 = [[UIMenuItem alloc]initWithTitle:@"分享" action:@selector(shareText)];
    UIMenuController *menu = [UIMenuController sharedMenuController];
    menu.menuItems = @[menuItem2,menuItem22,menuItem4];
    [menu setMenuVisible:YES animated:YES];
    [self.textView startScrolling];
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(highlighted) || action == @selector(cancelHighlighted)) {
        NSRange selectedRange = self.textView.selectedRange;//当前选择的文字在本页面的位置
        NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getHighlightMarkChapterId:readSchedule.chapterId];
        BOOL isHighlightMark = NO;
        for (HighlightMark *highlightMark in highlightMarks) {
            NSRange mrang = NSIntersectionRange(NSRangeFromString(highlightMark.rang), selectedRange);
            if (mrang.length>0) {
                isHighlightMark = YES;
                self.textView.selectedRange = NSRangeFromString(highlightMark.rang);//当前高亮的文字在本页的位置
                break;
            }
        }
        if (action == @selector(highlighted)) {
            return !isHighlightMark;
        }else{
            return isHighlightMark;
        }
    }else if (action == @selector(bookNote) || action == @selector(deleteBookNote)) {
        return YES;
    }else if (action == @selector(shareText)) {
        return YES;
    }else{
        return NO;
    }
}
#pragma mark 添加高亮
-(void)highlighted{
    NSRange selectedRange = self.textView.selectedRange;
    HighlightMark *highlightMark = [HighlightMark new];
    highlightMark.articleid = readSchedule.articleid;
    highlightMark.chapterId = readSchedule.chapterId;
    highlightMark.rang = NSStringFromRange(selectedRange);
    highlightMark.textString = [chapterText.chapterTextString substringWithRange:selectedRange];
    [[ZMYLKDB getLKDBHelper]insertToHighlightMarkDB:highlightMark];
    [self setTextHighlighted];
}
#pragma mark 取消高亮
-(void)cancelHighlighted{
    NSRange selectedRange = self.textView.selectedRange;
    NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getHighlightMarkChapterId:readSchedule.chapterId];
    for (HighlightMark *highlightMark in highlightMarks) {
        NSRange mrang = NSIntersectionRange(NSRangeFromString(highlightMark.rang), selectedRange);
        if (mrang.length>0) {
            [[ZMYLKDB getLKDBHelper]deleteToHighlightMarkDB:highlightMark];
            break;
        }
    }
    [self setTextHighlighted];
}
#pragma mark 添加笔记
-(void)bookNote{
    
}
#pragma mark 删除笔记
-(void)deleteBookNote{
    
}
#pragma mark 分享文字
-(void)shareText{
    
}
#pragma mark 刷新页面的高亮文字
- (void)setTextHighlighted{
    NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getHighlightMarkChapterId:readSchedule.chapterId];
    NSMutableAttributedString *attributedText = [self getStringAttributed];
    for (HighlightMark *highlightMark in highlightMarks) {
            [attributedText addAttribute:NSForegroundColorAttributeName value:RGB_COLOR(116, 178, 77) range:NSRangeFromString(highlightMark.rang)];
    }
    [self.textView setAttributedText:attributedText];
    [self.textView scrollRangeToVisible:NSRangeFromString(readSchedule.rang)];
//    NSArray *tc = self.textView.layoutManager.textContainers;
//    CGRect visibleRect = [self.textView.layoutManager boundingRectForGlyphRange:NSRangeFromString(readSchedule.rang) inTextContainer:tc[0]];
//    [self.textView scrollRectToVisible:visibleRect animated:NO];
}
-(NSMutableAttributedString *)getStringAttributed{
    if (!chapterText) {
        return nil;
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple  = 1.3f;                    // 可变行高,乘因数
    paragraphStyle.lineSpacing         = 1.0f;                    // 行间距
    paragraphStyle.paragraphSpacing    = 1.0f;                   // 段间距
    paragraphStyle.alignment           = NSTextAlignmentLeft;    // 对齐方式
    paragraphStyle.tailIndent          = SCREEN_WIDTH-30;                    // 文本宽度
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSTextStorage *text = [[NSTextStorage alloc]initWithString:chapterText.chapterTextString];
    [text addAttribute:NSParagraphStyleAttributeName
                 value:paragraphStyle
                 range:NSMakeRange(0, text.length)];
    // 字体属性
    [text addAttribute:NSFontAttributeName
                 value:[UIFont systemFontOfSize:[ReadConfig currentAccount].foutSize]
                 range:NSMakeRange(0, text.length)];
    
    [text addAttribute:NSForegroundColorAttributeName
                 value:[ReadConfig currentAccount].textColor
                 range:NSMakeRange(0, text.length)];
    return text;
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    CGFloat percent = scrollView.contentOffset.y/(scrollView.contentSize.height-scrollView.frame.size.height);
    self.percentageLabel.text = [NSString stringWithFormat:@"%.1f%%",percent*100];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        [self.textView startScrolling];
    }
}
-(void)setPointsPerSecond:(CGFloat)pointsPerSecond{
    _pointsPerSecond = pointsPerSecond;
    self.textView.pointsPerSecond = _pointsPerSecond;
    [self.textView startScrolling];
    [ReadConfig currentAccount].pointsPerSecond = pointsPerSecond;
}
-(CGFloat)pointsPerSecond{
    _pointsPerSecond = self.textView.pointsPerSecond;
    return _pointsPerSecond;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.textView startScrolling];
}

//保存当前阅读进度
-(void)saveReadSchedule{
    CGRect visibleRect = [self.textView convertRect:self.textView.bounds toView:self.textView];
    NSArray *tc = self.textView.layoutManager.textContainers;
    NSRange rang = [self.textView.layoutManager glyphRangeForBoundingRect:visibleRect inTextContainer:tc[0]];
    readSchedule.rang = NSStringFromRange(rang);
    [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSchedule];
    if ([self.delegate respondsToSelector:@selector(updateBookmarkImage:)]) {
        [self.delegate updateBookmarkImage:NSStringFromRange(rang)];
    }
}
-(void)clickMiddleDetect{
    [self saveReadSchedule];
    if ([self.delegate respondsToSelector:@selector(clickMiddleDetect)]) {
        [self.delegate clickMiddleDetect];
    }
    if ([self.textView isScroll]) {
        [self.textView stopScrolling];
    } else {
        [self.textView startScrolling];
    }
    
}
-(void)clickLeftDetect{
    [self saveReadSchedule];
    if ([self.delegate respondsToSelector:@selector(clickLeftDetect)]) {
        [self.delegate clickLeftDetect];
    }
    [self.textView stopScrolling];
}
-(void)clickRightDetect{
    [self saveReadSchedule];
    if ([self.delegate respondsToSelector:@selector(clickRightDetect)]) {
        [self.delegate clickRightDetect];
    }
    [self.textView stopScrolling];
}
@end
